<template>
  <div>
    <MainContent title="商家配置">
      <template #search-bar>
        <SearchBar inline>
          <template #toolbar>
            <el-form-item>
              <el-button type="primary" icon="Plus" @click="addStore"
                >新增</el-button
              >
            </el-form-item>
          </template>
        </SearchBar>
      </template>
      <el-table :data="state.tableData" stripe v-loading="state.isLoading">
        <el-table-column prop="storeName" label="商家名称" min-width="160" />
        <el-table-column prop="appKey" label="appKey" min-width="120" />
        <el-table-column prop="appSecret" label="appSecret" min-width="120" />
        <el-table-column prop="orderUrl" label="下单地址" min-width="120" />
        <el-table-column
          prop="productUrl"
          label="获取商家商品链接"
          min-width="160"
        />
        <el-table-column
          prop="productDetailUrl"
          label="获取商家商品详情链接"
          min-width="160"
        />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              class="ml-2"
              :active-value="1"
              :inactive-value="0"
              disabled
            />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button type="text" size="small" @click="editForm(scope.row)"
              >编辑</el-button
            >
            <el-button type="text" size="small" @click="delStore(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          v-model:currentPage="params.current"
          v-model:page-size="params.size"
          :page-sizes="[10, 20, 30, 40]"
          layout="sizes, prev, pager, next"
          :total="state.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </MainContent>
    <el-dialog
      class="dialog-form"
      v-model="dialogFormVisible"
      :title="title"
      width="50%"
      :before-close="resetForm"
    >
      <el-form :model="form" ref="storeForm" :rules="rules" label-width="135px">
        <el-form-item label="所属商家" prop="storeUserId">
          <el-select
            v-model="form.storeUserId"
            placeholder="请选择所属商家"
            clearable
            style="width: 100%"
            @change="getStoreName"
          >
            <el-option
              :label="item.storeName"
              :value="item.id"
              :key="item.id"
              v-for="item in storeList"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="appKey" prop="appKey">
          <el-input
            v-model="form.appKey"
            autocomplete="off"
            placeholder="appKey"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="appSecret" prop="appSecret">
          <el-input
            v-model="form.appSecret"
            autocomplete="off"
            placeholder="appSecret"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="下单地址" prop="orderUrl">
          <el-input
            v-model="form.orderUrl"
            autocomplete="off"
            placeholder="下单地址"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="商家商品链接" prop="productUrl">
          <el-input
            v-model="form.productUrl"
            autocomplete="off"
            placeholder="商家商品链接"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="商家商品详情链接" prop="productDetailUrl">
          <el-input
            v-model="form.productDetailUrl"
            autocomplete="off"
            placeholder="商家商品详情链接"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm()">取消</el-button>
          <el-button type="primary" @click="submitForm(storeForm, edit)"
            >保存</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted } from "vue";
import {
  getStoreInfos,
  storeConfigs,
  deleteStore,
  saveOrUpdateStore,
} from "@/api/system";
import type { FormInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
// filterTemplate,
const router = useRouter();
const route = useRoute();
const store = useStore();
const state = reactive({
  total: 0,
  isLoading: false,
  tableData: [] as Array<any>,
});
const params = ref({
  size: 10,
  current: 1,
});
let form = ref({
  id: "",
  storeUserId: "",
  storeName: "",
  merchantId: store.state.user.merchantId,
  appSecret: "",
  orderUrl: "",
  appKey: "",
  productUrl: "",
  productDetailUrl: "",
  status: 0,
});
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  params.value.size = val;
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  params.value.current = val;
};
const getStoreName = () => {
  form.value.storeName = storeList.value.filter((i) => {
    return (i.id = form.value.storeUserId);
  })[0].storeName;
};
let storeList = ref([] as Array<any>);
const storeForm = ref<FormInstance>();
let edit = ref(false);
const rules = reactive({
  storeUserId: [
    {
      required: true,
      message: "请选择所属商家",
      trigger: "blur",
    },
  ],
  appKey: [
    {
      required: true,
      message: "请输入appKey",
      trigger: "blur",
    },
  ],
  appSecret: [
    {
      required: true,
      message: "请输入appSecret",
      trigger: "blur",
    },
  ],
  orderUrl: [
    {
      required: true,
      message: "请输入下单地址",
      trigger: "blur",
    },
  ],
  productUrl: [
    {
      required: true,
      message: "请输入商家商品链接",
      trigger: "blur",
    },
  ],
  productDetailUrl: [
    {
      required: true,
      message: "请输入商家商品详情链接",
      trigger: "blur",
    },
  ],
  status: [
    {
      required: true,
      message: "请选择是否启用",
      trigger: "blur",
    },
  ],
});
const dialogFormVisible = ref(false);

let title = ref("新增商家配置信息");

const addStore = () => {
  title.value = "新建商家配置信息";
  edit.value = false;
  dialogFormVisible.value = true;
};
const getStorePageList = async (): Promise<void> => {
  state.isLoading = true;
  const rs: any = await storeConfigs();
  if (rs.code == 200) {
    state.tableData = rs.payload;
  }
  state.isLoading = false;
};
const editForm = async (val: any): Promise<void> => {
  Object.assign(form.value, {
    ...val,
  });
  title.value = "编辑商家配置信息";
  edit.value = true;
  dialogFormVisible.value = true;
};
const submitForm = (formEl: FormInstance | undefined, edit: any) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      const rs: any = await saveOrUpdateStore(form.value);
      if (rs.code == 200) {
        resetForm();
        getStorePageList();
      }
    } else {
      console.log("报错啦！请重新使一下", fields);
    }
  });
};
const resetForm = () => {
  form.value = {
    id: "",
    storeUserId: "",
    storeName: "",
    merchantId: store.state.user.merchantId,
    appSecret: "",
    orderUrl: "",
    appKey: "",
    productUrl: "",
    productDetailUrl: "",
    status: 0,
  };
  storeForm.value?.resetFields();
  dialogFormVisible.value = false;
};

const delStore = (id: string | number) => {
  ElMessageBox.confirm("是否确定删除商家配置信息", "确认提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const rs: any = await deleteStore({
        id: id,
      });
      if (rs.code == 200) {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        getStorePageList();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
};
const getStoreList = async (): Promise<void> => {
  const rs: any = await getStoreInfos({
    merchantId: store.state.user.merchantId,
  });
  if (rs.code == 200) {
    storeList.value = rs.payload;
  }
};
onMounted(() => {
  getStorePageList();
  getStoreList();
});
</script>
<style lang="scss" scoped>
:deep(.el-form) {
  text-align: left;
  margin-top: 18px;
}

:deep(.el-table) {
  margin: 0 auto;
}
.page {
  margin: 10px auto;
}
.dialog-form {
  :deep(.el-date-editor) {
    width: 100%;
  }
}
:deep(.el-radio-group) {
  display: block;
}
:deep(.el-radio) {
  display: block;
}
.intro {
  display: inline-block;
  margin-left: 30px;
}
</style>
